import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { updateUser } from "@/store/searchUser/searchUserAPI";
import { changeModal, getUserAsync } from "@/store/searchUser/searchUserSlice";
import { Form, Input, Modal, Select } from "antd";
import { useEffect, useState } from "react";

export default function Create() {
  const [loading, setLoading] = useState<boolean>(false);
  const { modal, table } = useAppSelector((state) => state.searchUser);
  const {
    config: { data: { data: { backend_modify_type = [] } = {} } = {} } = {},
  } = useAppSelector((state) => state.app);
  const [form] = Form.useForm();
  const dispatch = useAppDispatch();
  const handleClose = () => {
    form.resetFields();
    dispatch(changeModal({ open: false }));
  };
  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      updateUser(values)
        .then(() => {
          handleClose();
          dispatch(
            getUserAsync({ query_user_id: table.data?.data?.user_id as string })
          );
        })
        .finally(() => setLoading(false));
    } catch (err) {
      console.error("校验不通过");
    }
  };

  useEffect(() => {
    if (modal.open) {
      form.setFieldValue("query_user_id", table.data?.data?.user_id);
    }
  }, [modal]);

  return (
    <Modal
      title="修改数据"
      open={modal.open}
      onOk={handleOk}
      confirmLoading={loading}
      onCancel={handleClose}
    >
      <Form form={form}>
        <Form.Item
          name="query_user_id"
          label="用户ID"
          rules={[{ required: true, message: "必填" }]}
        >
          <Input disabled />
        </Form.Item>
        <Form.Item
          name="m_type"
          label="修改类型"
          rules={[{ required: true, message: "必填" }]}
        >
          <Select options={backend_modify_type} />
        </Form.Item>
        <Form.Item
          name="param"
          label="参数"
          rules={[{ required: true, message: "必填" }]}
        >
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
}
